<template>
  <transition name="el-fade-in">
    <l-layout class="l-tab-page" v-show="!lr_loadPage">
      <template #left>
        <l-panel style="padding-right: 0">
          <template #title>
            {{$t('大屏分类')}}
            <div class="tree-setting-btn">
              <el-tooltip effect="dark" :content="$t('分类管理')" placement="top">
                <i @click="handleSettingClick" class="el-icon-setting"></i>
              </el-tooltip>
            </div>
          </template>
          <div class="l-rblock" style="padding-bottom: 32px">
            <div class="l-rblock" style="overflow: hidden auto">
              <el-tree
                v-loading="treeLoading"
                :data="treeShowData"
                :expand-on-click-node="false"
                @node-click="handleNodeClick"
              >
                <span class="lr-tree-node" slot-scope="{ node }">
                  <i class="el-icon-notebook-2"></i>
                  {{ node.label }}
                </span>
              </el-tree>
            </div>
            <div class="l-bottom">
              <el-input
                :placeholder="$t('请输入名称')"
                @keyup.enter.native="hanleSearchCategory"
                v-model="searchCategoryWord"
                size="mini"
              >
                <el-button
                  @click="hanleSearchCategory"
                  slot="append"
                  icon="el-icon-search"
                ></el-button>
              </el-input>
            </div>
          </div>
        </l-panel>
      </template>
      <l-panel style="padding-left: 0" class="nobg">
        <template #toolLeft>
          <div class="l-panel--item">
            <el-input
              :placeholder="$t('请输入编码/名称')"
              @keyup.enter.native="hanleSearch"
              v-model="searchWord"
              size="mini"
            >
              <el-button
                @click="hanleSearch"
                slot="append"
                icon="el-icon-search"
              ></el-button>
            </el-input>
          </div>
        </template>
        <template #toolRight>
          <l-tool-btns @click="handleAdd()" :btnText="$t('新建大屏')"> </l-tool-btns>
          <swiper-btn></swiper-btn>
        </template>
        <div
          class="l-rblock"
          style="padding-bottom: 48px; background-color: #f0f2f5"
          v-loading="tableLoading"
        >
          <div class="l-rblock l-overflow-y">
            <div
              class="l-v-item"
              v-for="(item, index) in tableData"
              :key="item.f_Id"
            >
              <el-image
                v-if="item.f_Id"
                :src="`${apiUrl}system/annexesfile/${item.f_Id}?token=${token}`"
              >
              <div slot="error" class="image-slot">
                <img src="../../assets/error.jpg">
            </div>
              </el-image>
              <div class="content__btn" @click="handleDesign(item)">{{ $t('设计') }}</div>
              <div style="position: absolute; top: 8px; right: 8px">
                <el-switch
                  :active-value="1"
                  :inactive-value="0"
                  v-model="item.f_Status"
                  @change="handleEnableChange(item)"
                >
                </el-switch>
              </div>
              <div class="content__main">
                <!-- <span class="content__name" style="white-space:nowrap;">{{ item.f_Title }}</span> -->
                <a href="javascript:;" :title="item.f_Title" style="display:inline-block;width:140px;overflow:hidden;
                text-overflow:ellipsis;white-space:nowrap;text-decoration:none;color:#fff;">{{item.f_Title}}</a>
                <div class="content__menulist">
                  <div class="content__view">
                    <el-tooltip :content="$t('删除')">
                      <i
                        class="el-icon-delete"
                        @click="handleDelete(item, index)"
                      ></i>
                    </el-tooltip>
                    <el-tooltip :content="$t('编辑')">
                      <i
                        class="el-icon-edit"
                        @click="handleEdit(item, index)"
                      ></i>
                    </el-tooltip>
                    <el-tooltip :content="$t('发布')">
                      <i
                        class="el-icon-position"
                        @click="handleViews(item, index)"
                      ></i>
                    </el-tooltip>
                    <el-tooltip :content="$t('复制')">
                      <i
                        class="el-icon-copy-document"
                        @click="handleCopy(item, index)"
                      ></i>
                    </el-tooltip>
                  </div>
                  <!-- :class="{'content__status--active':item.f_Status}" -->
                  <!-- <span class="content__status">
                    {{ item.f_Status ? "已发布" : "未发布" }}
                  </span> -->
                </div>
              </div>
            </div>
          </div>
          <div class="l-table--pagination" style="border: 0">
            <el-pagination
              layout="total, sizes, prev, pager, next, jumper"
              background
              :page-sizes="[10, 20, 30, 50]"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :page-size="tablePageSize"
              :current-page.sync="tableCurrentPage"
              :total="tableTotal"
            >
            </el-pagination>
          </div>
        </div>
      </l-panel>

      <l-drawer
        :title="$t('分类管理')"
        :visible.sync="categoryVisible"
        :showOk="false"
        :showClose="false"
        size="800px"
      >
        <l-dataitem-index classifyCode="DaatavSort"></l-dataitem-index>
      </l-drawer>
      <l-drawer
        :title="formTitle"
        :visible.sync="formVisible"
        @ok="handleSave"
        @close="handleCloseForm"
        @opened="handleOpenedForm"
      >
        <visual-form ref="form" :categoryData="treeData"></visual-form>
      </l-drawer>

      <!--预览配置-->
      <l-fullscreen-dialog
        :title="$t('预览配置')"
        :headerMidWidth="320"
        :visible.sync="formViewVisible"
        :isStep="true"
        :steps="[$t('基本配置'), $t('大屏预览')]"
        :stepActive.sync="stepActive"
        :validateSteps="handleValidateSteps"
        @ok="handleSaveView"
        @closed="handleCloseViewForm"
        @opened="handleOpenedViewForm"
      >
        <preview-form ref="preForm" :stepActive="stepActive"> </preview-form>
      </l-fullscreen-dialog>
    </l-layout>
  </transition>
</template>

<script>
import visualForm from "./form";
import previewForm from "./previewForm";
import swiperBtn from "./swiperBtn.vue";
const api = window.$api.vdata.visual;
const api2 = window.$api.vdata.vconfig;
export default {
  name: "visual-index",
  components: {
    visualForm,
    swiperBtn,
    previewForm,
  },
  props: {},
  data() {
    return {
      //查询
      searchWord: "",
      searchTableData: null,

      treeLoading: false,
      treeData: [],
      treeShowData: [],
      searchCategoryWord: "",
      categoryVisible: false,
      categoryId: "",

      tableLoading: false,
      tableData: [],
      tableTotal: 0,
      tablePageSize: 30,
      tableCurrentPage: 1,

      formVisible: false,
      formTitle: "",
      formEditRow: null,
      formEdit: false,
      formViewVisible: false,
      stepActive: 0,
    };
  },
  created() {
    this.loadTablePageData();
  },
  mounted() {
    this.lr_loadDataItem("DaatavSort");
  },
  computed: {
    dataItemTree_Function() {
      return this.lr_dataItemTree(this.lr_dataItem["DaatavSort"]);
    },
  },
  watch: {
    dataItemTree_Function: {
      handler(n) {
        this.treeData = n;
        this.treeShowData = n;
      },
      immediate: true,
      deep: true,
    },
  },
  methods: {
    refreshCategory(data) {
      this.searchCategoryWord = "";
      this.treeData = [];
      data.forEach((item) => {
        this.treeData.push({ value: item.value, label: item.label });
      });
      this.treeShowData = this.treeData;
    },
    loadCategory() {
      this.treeData = [];
      this.lr_dataItemTree(this.lr_dataItem["DaatavSort"]).forEach((item) => {
        this.treeData.push({ value: item.value, label: item.label });
      });
    },
    hanleSearchCategory() {
      if (this.searchCategoryWord) {
        this.treeShowData = this.treeData.filter(
          (item) => item.label.indexOf(this.searchCategoryWord) > -1
        );
      } else {
        this.treeShowData = this.treeData;
      }
    },
    handleSettingClick() {
      this.categoryVisible = true;
    },
    handleCurrentChange(val) {
      this.tableCurrentPage = val;
      this.loadTablePageData();
    },
    handleSizeChange(val) {
      this.tablePageSize = val;
      this.loadTablePageData();
    },
    loadTablePageData() {
      this.tableLoading = true;
      let queryData = {
        rows: this.tablePageSize,
        page: this.tableCurrentPage,
        sidx: "F_CreateDate DESC",
        keyword: this.searchWord,
        F_Category: this.categoryId,
      };
      api
        .getPage(queryData)
        .then((res) => {
          const data = this.$deepClone(res.data.data);
          this.tableData = data.rows;
          this.tableTotal = data.records;

          this.tableLoading = false;
        })
        .catch(() => {
          this.tableData = [];
          this.tableLoading = false;
        });
    },
    turnTablePage({ rows, page }) {
      this.tablePageSize = rows;
      this.tableCurrentPage = page;
      this.loadTablePageData();
    },

    handleNodeClick(data) {
      this.categoryId = data.value;
      this.loadTablePageData();
    },

    refreshTable() {
      this.searchWord = "";
      this.searchTableData = null;
      this.lr_updateDataItemDetails(this.classifyCode, "tableLoading").then(
        (res) => {
          this.tableData = res;
        }
      );
    },

    hanleSearch() {
      this.loadTablePageData();
    },
    async handleEnableChange(row) {
      await api.updateState(row.f_Id, row.f_Status);
      this.$message({
        type: "success",
        message: this.$t("更新成功!"),
      });
      this.updateModules();
    },
    handleDesign(item) {
      let routeUrl = this.$router.resolve({
        path: `/vdata/build?id=${item.f_Id}`,
      });
      window.open(routeUrl.href, "_blank");
    },

    handleAdd() {
      this.formEdit = false;
      this.showForm("新建大屏");
    },
    handleEdit(item) {
      this.formEdit = true;
      this.formEditRow = item;
      this.showForm("编辑大屏");
    },
    handleDelete(row) {
      this.$confirm(this.$t("此操作将永久删除该数据, 是否继续?"), this.$t("提示"), {
        confirmButtonText: this.$t("确定"),
        cancelButtonText: this.$t("取消"),
        type: "warning",
      })
        .then(() => {
          api
            .delObj(row.f_Id)
            .then(() => {
              this.$message({
                type: "success",
                message: this.$t("删除成功!"),
              });
              this.loadTablePageData();
            })
            .catch(() => {});
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: this.$t("已取消删除"),
          });
        });
    },
    handleCopy(item) {
      this.$confirm("确认复制当前大屏?", "提示", {
        confirmButtonText: this.$t("确定"),
        cancelButtonText: this.$t("取消"),
        type: "warning",
      })
        .then(() => {
          api2
            .copyObj(item.f_Id)
            .then(() => {
              this.$message({
                type: "success",
                message: this.$t("复制成功!"),
              });
              this.loadTablePageData();
            })
            .catch(() => {});
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: this.$t("已取消复制"),
          });
        });
    },
    handleViews(item) {
      this.formViewVisible = true;
      this.formEditRow = item;
    },

    handleSave(showLoading, hideLoading) {
      this.$refs.form.validateForm(() => {
        showLoading();
        const formData = this.$refs.form.getForm();
        if (this.formEdit) {
          // 修改数据
          api
            .updateObj(formData.f_Id, formData)
            .then(() => {
              hideLoading();
              this.formVisible = false;
              this.$message({
                type: "success",
                message: this.$t("更新成功!"),
              });
              this.loadTablePageData();
            })
            .catch(() => {
              hideLoading();
            });
        } else {
          // 新增数据
          const data = {
            lrDatavVisualEntity: {
              f_Password: formData.f_Password,
              f_Category: formData.f_Category,
              f_Title: formData.f_Title,
              f_Status: formData.f_Status,
            },
            lrDatavVisualconfigList: [
              {
                f_Detail: JSON.stringify({
                  name: formData.f_Title,
                  width: 1920,
                  height: 1080,
                  scale: 1,
                  backgroundImage: "",
                  url: "",
                  mark: {},
                  gradeShow: false,
                  gradeLen: 30,
                }),
                f_Component: "[]",
              },
            ],
          };
          api
            .addObj(data)
            .then(() => {
              hideLoading();
              this.formVisible = false;
              this.$message({
                type: "success",
                message: this.$t("添加成功!"),
              });
              this.loadTablePageData();
              // this.$nextTick(() => {
              //     console.log(res.data.data, 'res.data.data')
              //     let routeUrl = this.$router.resolve({
              //         path: `/vdata/build?id=${res.data.data}`
              //     })
              //     window.open(routeUrl.href, '_blank');
              // });
            })
            .catch(() => {
              hideLoading();
            });
        }
      });
    },
    handleOpenedForm() {
      if (this.formEdit) {
        this.$refs.form.setForm(this.formEditRow);
      }
    },
    handleCloseForm() {
      this.$refs.form.resetForm();
    },
    showForm(text) {
      this.loadCategory();
      this.formTitle = text;
      this.formVisible = true;
    },
    handleValidateSteps() {
      return this.$refs.preForm.validateSteps();
    },

    updateModules() {
      this.$store.dispatch("system/module/getList");
    },
    async handleSaveView() {
        let isSave = true
        await this.$refs.preForm.validateBaseInfo().then(res=>{
            isSave = res
        })
        if (!isSave) return
      const loading = this.$loading({
        lock: true,
        text: this.$t("正在保存配置，请稍后"),
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.2)",
      });
        
      this.$nextTick(async () => {
        const postData = await this.$refs.preForm.getForm();
        let res = null;
          res = await api.setmodule(postData)
        if (res) {
          this.$message({
            type: "success",
            message: this.$t("设置成功!"),
          });
          this.formViewVisible = false;
            this.loadTablePageData();
            this.updateModules();
        }
        loading.close();
      });
    },
    handleCloseViewForm() {
    },
    async handleOpenedViewForm(showLoading, hideLoading) {
      showLoading("加载数据中...");
        const data = await this.$awaitWraper(api.get(this.formEditRow.f_Id));
        this.$refs.preForm.setForm(data);
        hideLoading();
    },
  },
};
</script>